import base64
import datetime
import os
import requests
from bs4 import BeautifulSoup


def cache_attrs(days=1):
    """缓存方法返回值的装饰器"""

    def _wrapper(func):
        _cache = None
        _expiry = None

        def _inner(*args, **kwargs):
            nonlocal _expiry
            nonlocal _cache

            # 如果有缓存并且没有过期就返回缓存
            if _cache is not None and _expiry is not None:
                if datetime.datetime.now() < _expiry:
                    return _cache

            _expiry = datetime.datetime.now() + datetime.timedelta(days=days)
            _cache = func(*args, **kwargs)
            return _cache

        return _inner

    return _wrapper


def get_content(url):
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
                      'AppleWebKit/537.36 (KHTML, like Gecko) ' +
                      'Chrome/93.0.4577.82 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    content = response.content
    return content


@cache_attrs(days=1)  # days=1 表示缓存过期时间为一天
def get_zx_portal_banners():
    url = 'http://www.nbzx.gov.cn'
    content = get_content(url)
    html = content.decode('utf-8')

    # html解析
    bs = BeautifulSoup(html, "html.parser")
    selection = bs.select_one('#slide_x > div.box > ul')
    li_tags = selection.select('li')

    # 提取数据
    attrs = []
    for li in li_tags:
        src = url + li.a.img['src']
        attrs.append({
            'href_attr': url,
            'title_attr': li.a['title'],
            'src_attr': src,
            'img_url': '/' + save_img(src),
        })
    return attrs


def save_img(url):
    content = get_content(url)

    img_name = url.split('/')[-1]
    path = 'static/zx_portal'
    if not os.path.exists(path):
        os.makedirs(path)

    img_path = path + '/%s' % img_name
    with open(img_path, 'wb') as f:
        f.write(content)

    return img_path


def get_img_base64(url):
    content = get_content(url)
    _base64 = base64.b64encode(content)
    return _base64.decode('utf-8')
